package logic

import (
	"context"
	"develop/model/cache"
	"develop/model/mysql"
	"develop/pkg"
	"errors"

	"develop/usersrpc/internal/svc"
	"develop/usersrpc/usersrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *usersrpc.LoginRequest) (*usersrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var findPhoneId mysql.User_info
	err := findPhoneId.FindPhoneId(mysql.DB, in.PhoneNum)
	if err != nil {
		return nil, err
	}
	if findPhoneId.ID == 0 {
		return nil, errors.New("该手机号未注册，请前往注册")
	}
	if in.LoginType == 1 || in.LoginType == 2 {
		if in.LoginType == 1 {
			if pkg.Md5(in.Pwd) != findPhoneId.Pwd {
				return nil, errors.New("密码错误")
			}
		}
		if in.LoginType == 2 {
			result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.PhoneNum).Result()
			if result != in.SendSmsCode {
				return nil, errors.New("短信验证码不正确")
			}
		}
	} else {
		return nil, errors.New("请选择正确的登录方式")
	}
	if in.AccountStatus == 1 {
		return nil, errors.New("账号已禁用，请联系管理员")
	}

	return &usersrpc.LoginResponse{
		UserId: int64(findPhoneId.ID),
	}, nil
}
